#include "tcpserver.h"

TcpServer::TcpServer(QObject *parent, int port): QTcpServer(parent)
{
    listen(QHostAddress::Any, port);
}


//将连接成功的客户端保存下来
void TcpServer::incomingConnection(qintptr handle)
{
    TcpServerSocket *tcpserversocket = new TcpServerSocket(this);

    connect(tcpserversocket, SIGNAL(updateServer(QString, int)), this, SLOT(updateClients(QString, int)));
    connect(tcpserversocket, SIGNAL(disconnected(int)), this, SLOT(slotDistconnected(int)));

    tcpserversocket->setSocketDescriptor(handle);
    tcpServerSocketList.append(tcpserversocket);
}

void TcpServer::updateClients(QString msg, int length)
{
    emit updateServer(msg, length);
    for(int i = 0; i < tcpServerSocketList.count(); i++)
    {
        TcpServerSocket *item = tcpServerSocketList.at(i);
        if(item->write(msg.toLatin1(), length) != length)
        {
            continue;
        }
    }
}

void TcpServer::slotDistconnected(int descriptor)
{
    for(int i = 0; i < tcpServerSocketList.count(); i++)
    {
        TcpServerSocket *item = tcpServerSocketList.at(i);
        if(item->socketDescriptor() == descriptor)
        {
            tcpServerSocketList.removeAt(i);
            return ;
        }
    }
    return ;
}
